import { createRouter, createWebHashHistory } from 'vue-router'
import Login from '@/views/Login'
import Home from '@/views/Home'
import test from '@/views/test'
import Welcome from '@/views/Welcome'
import Users from '@/views/Users'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    redirect: Login
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: Welcome
      },
      {
        path: '/users',
        name: 'Users',
        component: Users
      }
    ]
  },
  {
    path: '/test',
    name: 'test',
    component: test
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 挂载路由守卫
router.beforeEach((to, from, next) => {
  // to将要访问的路径
  // from 代表从哪个路径跳转
  // 而来next是一个函数，表示放行
  // next()放行     next( ' / login ')强制跳转
  if (to.path === '/login') return next()
  if (to.path === '/test') return next()

  // 获取token
  const token = window.sessionStorage.getItem('token')
  // 无token,强制跳转
  if (!token) return next('/login')
  // 放行
  next()
})

export default router
